package com.example.algorithm_learning_platform.service.impl;

import com.example.algorithm_learning_platform.entity.ChatMessage;
import com.example.algorithm_learning_platform.mapper.ChatMessageMapper;
import com.example.algorithm_learning_platform.service.ChatService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.time.Duration;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatServiceImpl implements ChatService {

    private final ChatMessageMapper chatMessageMapper;
    private final ObjectMapper objectMapper;
    
    @Value("${openai.api-key}")
    private String apiKey;
    
    @Value("${openai.base-url}")
    private String baseUrl;
    
    @Value("${openai.proxy.host:127.0.0.1}")
    private String proxyHost;
    
    @Value("${openai.proxy.port:7890}")
    private Integer proxyPort;

    private OkHttpClient createClient() {
        return new OkHttpClient.Builder()
                .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
                .connectTimeout(Duration.ofSeconds(60))
                .readTimeout(Duration.ofSeconds(60))
                .writeTimeout(Duration.ofSeconds(60))
                .build();
    }

    @Override
    public ChatMessage chat(String question, Integer userId) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setUserId(userId);
        chatMessage.setQuestion(question);
        
        try {
            // 构建请求体
            String json = String.format("""
                    {
                      "max_tokens": 1200,
                      "model": "gpt-3.5-turbo",
                      "temperature": 0.8,
                      "top_p": 1,
                      "presence_penalty": 1,
                      "messages": [
                        {
                          "role": "system",
                          "content": "You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible."
                        },
                        {
                          "role": "user",
                          "content": "%s"
                        }
                      ]
                    }""", question);

            // 创建请求
            RequestBody body = RequestBody.create(json, MediaType.parse("application/json"));
            Request request = new Request.Builder()
                    .url(baseUrl + "/v1/chat/completions")
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .build();

            // 发送请求
            try (Response response = createClient().newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    String errorBody = response.body() != null ? response.body().string() : "";
                    log.error("API调用失败: {} {} - {}", response.code(), response.message(), errorBody);
                    throw new RuntimeException("API调用失败: " + response.code() + " " + response.message());
                }
                
                String responseBody = response.body().string();
                log.debug("API响应: {}", responseBody);
                JsonNode jsonNode = objectMapper.readTree(responseBody);
                String answer = jsonNode.path("choices").get(0).path("message").path("content").asText();
                chatMessage.setAnswer(answer);
            }
        } catch (Exception e) {
            log.error("调用AI服务失败", e);
            String errorMessage = e.getMessage();
            if (e instanceof java.net.SocketTimeoutException) {
                errorMessage = "请求超时，请稍后重试";
            } else if (e instanceof java.net.SocketException) {
                errorMessage = "网络连接异常，请检查网络或代理设置";
            }
            chatMessage.setAnswer("抱歉，AI服务暂时不可用。" + errorMessage);
        }

        // 保存对话记录
        chatMessageMapper.insert(chatMessage);
        return chatMessage;
    }
} 